// web/src/app/auth.config.ts
import Credentials from "next-auth/providers/credentials";
import {LoginSchema} from "@/schemas";
import bcrypt from 'bcryptjs'
import {getUserByEmail} from "@/data/user";
import Github from 'next-auth/providers/github'
import Google from 'next-auth/providers/google'

export const authOptions = {
    providers: [
        Github({
            clientId: process.env.GITHUB_CLIENT_ID,
            clientSecret: process.env.GITHUB_CLIENT_SECRET,
        }),
        Google({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
        Credentials({
            name: 'Credentials',
            // You can specify which fields should be submitted, by adding keys to the `credentials` object.
            // e.g. domain, username, password, 2FA token, etc.
            credentials: {
                email: {label: 'Username', type: 'email', placeholder: "邮箱"},
                password: {label: 'Password', type: 'password', placeholder: "密码"},
            },
            // 登录验证方法
            authorize: async (credentials) => {
                const validatedFields = LoginSchema.safeParse(credentials);

                if (validatedFields.success) {
                    const {email, password} = validatedFields.data

                    // 查询数据库
                    const user = await getUserByEmail(email)
                    if (!user || !user.password) return null

                    const passwordsMatch = await bcrypt.compare(password, user.password)

                    if (passwordsMatch) {
                        return user
                    }
                }

                return null
            },
        }),
    ],
}
